package mysql;

import design_patterns.command.CommandQueue;
import utils.MyList;
import utils.titles.Title;
import mysql.ddl.queries.SelectFks;
import mysql.ddl.queries.SelectPks;
import mysql.ddl.queries.SelectTables;

import java.sql.SQLException;

/**
 * Created by thormentor on 27-04-2014.
 */
public class Schema extends MySQL.Object {

    private final Connection connection;
    private MyList<Table> tables = new MyList<>();

    public Schema(Connection connection) {
        super(Title.fromSnakeCase(connection.getSchemaName()));
        this.connection = connection;
    }

    public MyList<Table> getTables() {
        return tables;
    }

    public void extract() {
        try {
            connection.connect();

            CommandQueue queue = new CommandQueue();

            queue.add(new SelectTables(connection, this));
            queue.add(new SelectPks(connection, this));
            queue.add(new SelectFks(connection, this));

            queue.onFinish((a, b, c) -> {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            });

            queue.execute();
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String toString() {
        return connection.toString();
    }

    public Table getTable(String tableName) {
        return tables.get(tableName);

    }

    public Connection getConnection() {
        return connection;
    }

    public Table getTable(Title title) {
        return getTable(title.getSingularized().toSnakeCase());
    }
}
